package com.xiguanlezz.cn.common.utils;

import org.apache.commons.lang3.StringUtils;

/**
 * @Author：习惯了种种
 * @CreateDate：2024/11/19 20:54
 * @Description：网络地址解析工具类
 */
public class InternetAddressUtil {

    public static final String IP_PORT_SPLITER = ":";
    public static final String IPV6_START_MARK = "[";
    public static final String IPV6_END_MARK = "]";

    /**
     * IPV4地址和IPV6地址解析
     * 其中IPV6地址中的IP地址必须用"[]"包起来，同时对于IPV6解析后的IP地址中前后包含"[]"
     */
    public static String[] splitIPPortStr(String str) {
        if (StringUtils.isBlank(str)) {
            throw new IllegalArgumentException("ip and port string cannot be empty!");
        }
        String[] serverAddrArr;
        if (str.startsWith(IPV6_START_MARK) && StringUtils.containsIgnoreCase(str, IPV6_END_MARK)) {
            if (str.endsWith(IPV6_END_MARK)) {
                serverAddrArr = new String[1];
                serverAddrArr[0] = str;
            } else {
                serverAddrArr = new String[2];
                serverAddrArr[0] = str.substring(0, (str.indexOf(IPV6_END_MARK) + 1));
                serverAddrArr[1] = str.substring((str.indexOf(IPV6_END_MARK) + 2));
            }
        } else {
            serverAddrArr = str.split(IP_PORT_SPLITER);
        }
        return serverAddrArr;
    }
}

